<?php
class IeitemsModel extends CommonModel
{
	public function __construct($uid)
	{
		parent::__construct('ieitems');
		if(empty($uid) || intval($uid) != $uid){trigger_error("UID ERROR!");exit;}
	    $this->uid = $uid;
	}
	
	protected function _setFields()
	{
		return array(
			'AID',
			'UID',
			'PID',
			'ItemName',
			'ItemType',
			'Status',
			'CreateDate',
			'Remark'
		);
	}
	
	protected function _setPrimaryKeys()
	{
		return array(
			'AID'
		);
	}
	
	protected function _setAutoIncrementFields()
	{
		return array(
			'AID'
		);
	}
	
	protected function _setForeignKeyRelation()
	{
		return array();
	}
	
	public function add($data)
	{
		$data = $this->_getFieldsData($data);
		$dbMaster = DB::getMaster();
		$sql = "INSERT INTO `{$this->_table}`(`UID`,`PID`,`ItemName`,`ItemType`,`Status`,`CreateDate`,`Remark`) 
				VALUES('{$this->uid}','{$data['PID']}','{$data['ItemName']}','{$data['ItemType']}','{$data['Status']}','{$data['CreateDate']}','{$data['Remark']}')";
		$dbMaster->exec($sql);
		return !$dbMaster->isError();
	}
	
	public function getAll()
	{
		$dbSlave = DB::getSlave();
		$sql = "SELECT *,CONCAT(IF(PID!=0,'0-',''), PID, '-', AID) AS Path 
				FROM `mym_ieitems` 
				WHERE UID='{$this->uid}'
				ORDER BY CONCAT(IF(PID!=0,'0-',''), PID, '-', AID);";
		return $dbSlave->query($sql);
	}
	
	public function getTree()
	{
		$data = $this->getAll();
		$level = 0;
		$tree = array();
		$i = -1;
		foreach ($data as $k=>$d)
		{
			$level = substr_count($d['Path'], '-');
			if($level == 1)
			{
				$tree[++$i] = $d;
			}
			else
			{
				$tree[$i]['child'][] = $d;
			}
		}
		return $tree;
	}
	
	public function getById($id)
	{
		$id = intval($id);
		if(empty($id)) return array();
		$dbSlave = DB::getSlave();
		$sql = "SELECT * FROM `{$this->_table}` WHERE `AID`={$id} AND `UID`='{$this->uid}'";
		return $dbSlave->getRow($sql);
	}
	
	public function edit($aid, $data)
	{
	    $sql = "UPDATE `{$this->_table}` SET `ItemName`='{$data['ItemName']}', `Remark`='{$data['Remark']}' WHERE `AID`=$aid AND `UID`={$this->uid}";
	    $dbMaster = DB::getMaster();
	    $dbMaster->exec($sql);
	    return !$dbMaster->isError();
	}
	
	public function getALevel()
	{
		$dbSlave = DB::getSlave();
		$sql = "SELECT * FROM `{$this->_table}` WHERE UID='{$this->uid}' AND PID=0";
		return $dbSlave->query($sql);
	}

	protected function _validationField($fieldName, $value) 
	{
		return true;
	}
	
	public function __destruct()
	{
		//echo 'account model destruct!';
	}
}